package cn.quevo.core.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.quevo.core.entity.TreeNode;
import cn.quevo.core.exception.CheckParamsException;

/**
 * TreeNode构建
 *
 * @author July july_sky@foxmail.com
 * @version 1.0
 * @date 2018-03-09 16:28:22
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @return
 */
public class TreeNodeBuilder implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -6251430159583697502L;

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @param rootId
     * @return
     * @throws CheckParamsException
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:28:29
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static <T extends TreeNode> List<T> buildByRecursive(List<T> treeNodes, String rootId) throws CheckParamsException {
        List<T> trees = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (rootId.equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes, 1));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode
     * @param treeNodes
     * @return
     * @throws CheckParamsException
     * @author July july_sky@foxmail.com
     * @date 2018-03-09 16:28:35
     * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
     * @version 1.0
     */
    public static <T extends TreeNode> T findChildren(T treeNode, List<T> treeNodes, int loop) throws CheckParamsException {
        if (loop >= 20) {
            throw new CheckParamsException(7001, "请检查数据结构是否错误!!");
        }
        loop ++;
        for (T node : treeNodes) {
            if (treeNode.getId().equals(node.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(node, treeNodes, loop));
            }
        }
        return treeNode;
    }
}
